import React, { useState, useEffect, useRef, useCallback } from 'react';
import { List, Empty, message } from 'antd';
import { getMessage, TextWidget } from '@inbiz/react';
import { routerPrefix } from 'InbizConfig';
import { NewsProps } from '../index';
import NewsItem, { NewsItemViewProps } from './newsItem';
import { getNewsList as getNewsListData } from '../../../service';
import { useEvents } from '@inbiz/utils';

const NewsListView: React.FC<NewsProps> = (props) => {
  const { viewType, pageSize, newsKey, standOut } = props;
  const fixNewKey = Array.isArray(newsKey) ? newsKey : newsKey ? [newsKey] : [];
  const [total, setTotal] = useState(0);
  const [spList, setSpList] = useState<Array<News.NewsItem>>([]);
  const [current, setCurrent] = useState(1);
  const content = useRef(null);
  const [isInit, $init] = useState(false);
  const [configEvents] = useEvents(props.callBackEvents, props.emit)


  const getNewsList = useCallback(async (params: object) => {
    const newParams = (await configEvents.current?.onParams?.(params)) || params;
    const data = await (configEvents.current?.onRequest || getNewsListData)(newParams as any)
    return await configEvents.current?.onData?.(data) || data
  }, []);

  const getList = async (page: number, init?: boolean) => {
    const res: News.NewsList = await getNewsList({
      categoryId: fixNewKey?.map((item: any) => { return item.id }).toString(),
      pageIndex: page,
      pageSize,
      showNew: standOut?.isStandout,
      numNew: standOut?.threshold || undefined,
    });

    setTotal(res?.Total || 0);
    setSpList(res?.ContentList || []);
    init && $init(true)
  };

  useEffect(() => {
    getList(1, true);
  }, [newsKey, pageSize]);

  useEffect(() => {
    getList(current);
  }, [current]);

  const goMore = () => {
    const { origin, pathname, search } = window.location;
    if (!props.correlationPage) {
      message.warning(getMessage('news.tips.message_more_none'));
      return;
    }
    const [name] = props.correlationPage.split(',');
    window.open(`${origin}${pathname}${search}#${routerPrefix}${name}`);
  };

  if (['static', 'resume', 'bigCard', 'smallCard'].includes(viewType)) {
    const pagesize = pageSize ? pageSize : 10;
    return (
      <div ref={content} className="eform-new-list">
        <List
          pagination={
            pagesize < total && props.dataLoad !== 'more'
              ? {
                simple: true,
                onChange: (page) => {
                  setCurrent(page);
                },
                pageSize: pagesize,
                total,
                current,
                hideOnSinglePage: true,
              }
              : false
          }
          dataSource={spList as any || []}
          locale={{
            emptyText: fixNewKey.length && !isInit ? <Empty
              image={null}
              description={''}
            /> : (
              <Empty
                image={Empty.PRESENTED_IMAGE_SIMPLE}
                description={<TextWidget>News.noData</TextWidget>}
              />
            ),
          }}
          renderItem={(item: NewsItemViewProps) => <NewsItem {...{ ...item, ...props }} />}
        />
        {props.dataLoad === 'more' && props.showPosition === 'right-bottom' && total !== 0 && (
          <p className="news-list-see-more">
            <span onClick={goMore}>
              <TextWidget>{props.showText || ''}</TextWidget>&nbsp;{'>'}
            </span>
          </p>
        )}
      </div>
    );
  }
  return null;
};

export default NewsListView;
